package orm

import (
	"fmt"
	"time"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

// 实体之间外键关联: N v M
type Owner struct {
	// 继承 gorm中的 Model
	gorm.Model

	Name string `gorm:"index:unique;size:255"`
	// autoCreateTime | autoUpdateTime 自动插入时间戳
	Version time.Time `gorm:"autoCreateTime"`

	// foreignKey:OwerId : 指定Card表中外键 OwerId 字段;
	// references:ID : 指定被关联表的关联字段；
	// 默认为主键，也可更改为其他字段references:Name；当为非主键时需要加 index:unique
	Cards []Card `gorm:"foreignKey:ForeignKey;references:Name"`
}

type Card struct {
	gorm.Model
	Address    string
	Code       string
	ForeignKey string
}

var db3 *gorm.DB

func init() {
	dsn := "root:root@tcp(localhost:3306)/go_db?charset=utf8mb4&parseTime=true"
	db1, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic("failed to connect database")
	}
	db3 = db1
}

func main_9() {
	// 创建外键表
	db3.AutoMigrate(&Owner{}, &Card{})
	insert1()
	selectAssociation()
}

func insert1() {
	// Create
	db3.Create(&Owner{Name: "lisi",
		Cards: []Card{
			{Address: "陕西西安", Code: "712217"},
			{Address: "陕西西安", Code: "712217"},
		},
	})
}

func selectAssociation() {
	var owner Owner
	db3.First(&owner)
	fmt.Printf("owner: %v\n", owner)
	var cards []Card

	// Association("xxx"): 指关联实体中属性xxx
	db3.Model(&owner).Association("Cards").Find(&cards)
	fmt.Printf("cards: %v\n", cards)
}
